/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
 */
package td.steps;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

/**
 * @author Artem Shamsutdinov
 * 
 */
public class ServerSteps {
	private boolean gaeIsUp = false;

	@Given("GAE is not up")
	public boolean isGaeUp() {
		try {
			InetAddress address = InetAddress.getByName("localhost:8080");
			return address.isReachable(3000);
		} catch (UnknownHostException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
	}

	@Then("clear the local Data Store")
	public void clearLocalDataStore() throws ParserConfigurationException,
			SAXException, IOException {
		File dbFile = new File(getDbFileLocation());
		if (dbFile.exists()) {

		}
	}

	public String getDbFileLocation() throws ParserConfigurationException,
			SAXException, IOException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		InputStream in = new FileInputStream("pom.xml");
		Document doc = builder.parse(in);

		Node artifactId = findNodeByName(doc, "artifactId");
		Node version = findNodeByName(doc, "version");

		return "target/" + artifactId.getTextContent() + "-"
				+ version.getTextContent()
				+ "/WEB-INF/appengine-generated/local_db.bin";
	}

	private Node findNodeByName(Node node, String name) {
		if (name.equals(node.getNodeName())) {
			return node;
		} else {
			for (Node n = node.getFirstChild(); n != null; n = n.getNextSibling()) {
				Node found = findNodeByName(n, name);
				if (found != null) {
					return found;
				}
			}
		}
		return null;
	}
}
